package com.sqpoll.android.group;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.sqpoll.android.R;
import com.sqpoll.android.poll.Poll;
import com.sqpoll.android.poll.PollCreateActivity;
import com.sqpoll.android.poll.PollDetailActivity;
import com.sqpoll.android.poll.PollListAdapter;
import com.sqpoll.android.widget.PullToRefreshListView;
import com.sqpoll.android.widget.PullToRefreshListView.OnRefreshListener;

/**
 * The activity for group poll list.
 * 
 * @author Younggue Bae
 */
public class GroupPollListActivity extends SherlockFragmentActivity {

	public static final String TAG = "GroupPollListActivity";

	private PullToRefreshListView mListView;
	private PollListAdapter mAdapter;
	private LayoutInflater mInflater;
	private boolean mLockListView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group_poll_list);
		
		Intent intent = getIntent();
		String groupName = intent.getStringExtra("group.name");

		ActionBar actionBar = getSupportActionBar();
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(groupName);
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(true);

		// for dynamic list view
		List<Poll> items = loadItems();
		mLockListView = false;
		mAdapter = new PollListAdapter(this, R.layout.list_item_poll, items);
		mListView = (PullToRefreshListView) findViewById(R.id.list_view);
		
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mListView.addFooterView(mInflater.inflate(R.layout.dynamic_loading_list_footer, null));

		mListView.setOnRefreshListener(mRefreshListener);
		mListView.setOnItemClickListener(mItemClickListener);
		mListView.setOnScrollListener(mScrollListener);
		mListView.setAdapter(mAdapter);
	}

	OnRefreshListener mRefreshListener = new OnRefreshListener() {
		@Override
		public void onRefresh() {
			// Your code to refresh the list contents

			// ...

			// Make sure you call listView.onRefreshComplete()
			// when the loading is done. This can be done from here or any
			// other place, like on a broadcast receive from your loading
			// service or the onPostExecute of your AsyncTask.

			mListView.onRefreshComplete();
		}
	};

	OnItemClickListener mItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
			Poll currentItem = (Poll) mAdapter.getItem(position);
			String question = currentItem.getQuestion();
			//Toast.makeText(getBaseContext(), "Selected : " + question, Toast.LENGTH_SHORT).show();
			
			Intent intent = new Intent(getBaseContext(), PollDetailActivity.class);
			intent.putExtra("id", "test");
			intent.putExtra("type", "group");
			intent.putExtra("question", question);
			startActivity(intent);
		}
	};
	
	OnScrollListener mScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView v, int scrollState) {
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			int count = totalItemCount - visibleItemCount;			
			//Log.i(TAG, "count == " + count + ", firstVisibleItem == " + firstVisibleItem);

			if(firstVisibleItem >= count && totalItemCount != 0 && mLockListView == false) {
				Toast.makeText(getBaseContext(), "Loading next items", Toast.LENGTH_SHORT).show();
				Log.i(TAG, "Loading next items");
				addItems(5);
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_group_poll_list, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			// Intent intent = new Intent(this, MainActivity.class);
			// startActivity(intent);
			break;

		case R.id.menu_new_poll:
			//Toast.makeText(getBaseContext(), "Selected: New poll", Toast.LENGTH_SHORT).show();
			Intent intentPollCreate = new Intent(getBaseContext(), PollCreateActivity.class);
			startActivity(intentPollCreate);
			break;

		case R.id.menu_invite:
			//Toast.makeText(getBaseContext(), "Selected: Invite friends", Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(Intent.ACTION_SEND);

			intent.addCategory(Intent.CATEGORY_DEFAULT);
			intent.putExtra(Intent.EXTRA_SUBJECT, "subject here...");
			intent.putExtra(Intent.EXTRA_TEXT, "content here...");
			intent.putExtra(Intent.EXTRA_TITLE, "title here...");
			intent.setType("text/plain");    

			startActivity(Intent.createChooser(intent, getString(R.string.dialog_title_invite)));
			break;

		case R.id.menu_member_list:
			//Toast.makeText(getBaseContext(), "Selected: Member list", Toast.LENGTH_SHORT).show();
			
			String groupName = getIntent().getStringExtra("group.name");
			
			Intent intentMembers = new Intent(this, GroupMemberListActivity.class);
			intentMembers.putExtra("group.name", groupName);
			startActivity(intentMembers);
			
			break;

		case R.id.menu_edit_group:
			GroupEditDialogFragment dialogEdit = new GroupEditDialogFragment();
			dialogEdit.show(getSupportFragmentManager(), "GroupEditDialogFragment");
			break;

		case R.id.menu_exit_group:
			GroupExitDialogFragment dialogExit = new GroupExitDialogFragment();
			dialogExit.show(getSupportFragmentManager(), "GroupExitDialogFragment");
			break;
		}

		return true;
	}

	private List<Poll> loadItems() {
		Resources res = getResources();

		List<Poll> items = new ArrayList<Poll>();

		Poll item = new Poll();
		item.setPollImage(res.getDrawable(R.drawable.ic_3));
		item.setUsername("Sonya Cho");
		item.setCreateDate("1 day ago");
		item.setStatus("open");
		item.setQuestion("Do you like this food?");
		item.setCommentCount(10);
		item.setVoterCount(17);
		
		items.add(item);

		item = new Poll();
		item.setPollImage(res.getDrawable(R.drawable.ic_5));
		item.setUsername("Younggue Bae");
		item.setCreateDate("06.07");
		item.setStatus("open");
		item.setQuestion("Do you like this news?");
		item.setCommentCount(5);
		item.setVoterCount(10);
		
		items.add(item);
		
		item = new Poll();
		item.setPollImage(res.getDrawable(R.drawable.ic_6));
		item.setUsername("Sonya Cho");
		item.setCreateDate("1 day ago");
		item.setStatus("open");
		item.setQuestion("Do you like this food?");
		item.setCommentCount(10);
		item.setVoterCount(17);
		
		items.add(item);

		item = new Poll();
		item.setPollImage(res.getDrawable(R.drawable.ic_9));
		item.setUsername("Sonya Cho");
		item.setCreateDate("1 day ago");
		item.setStatus("open");
		item.setQuestion("Do you like this food?");
		item.setCommentCount(10);
		item.setVoterCount(17);
		
		items.add(item);

		item = new Poll();
		item.setPollImage(res.getDrawable(R.drawable.ic_10));
		item.setUsername("Sonya Cho");
		item.setCreateDate("1 day ago");
		item.setStatus("open");
		item.setQuestion("Do you like this food?");
		item.setCommentCount(10);
		item.setVoterCount(17);
		
		items.add(item);

		return items;
	}
	
	private void addItems(final int size) {
		// Set lock to prevent from calling repeatedly.
		mLockListView = true;
		
		Runnable run = new Runnable() {
			@Override
			public void run() {
				for(int i = 0 ; i < size ; i++) {
					Poll item = new Poll();
					item.setPollImage(getResources().getDrawable(R.drawable.ic_3));
					item.setUsername("Sonya Cho");
					item.setCreateDate("1 day ago");
					item.setStatus("open");
					item.setQuestion("Do you like this food?...");
					item.setCommentCount(10);
					item.setVoterCount(17);
					
					mAdapter.addItem(item);
				}
				
				// After finishing loading, notifies adapter and releases the lock.
				mAdapter.notifyDataSetChanged();
				mLockListView = false;
			}
		};
		
		Handler handler = new Handler();
		handler.postDelayed(run, 5000);
	}

}